<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;

/**
 * 登录接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd','third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('mobile');
        $password = $this->request->request('password');
        $type = $this->request->request('type');
        session('user_type',$type);

        if (!$account || !$password ) {
            $this->ajaxError('参数不完整');
        }
        $token = $this->auth->login($account, $password);
        if ($token) {

            $data = ['token' => $token];
            $this->ajaxSuccess($data);
        } else {
            $this->ajaxError($this->auth->getError());
        }
    }
    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $token = $this->auth->direct($user->id);
        } else {
            //$token = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            $this->ajaxError('该手机尚未注册');
        }
        if ($token) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['token' => $token];
            $this->ajaxSuccess($data);
        } else {
            $this->ajaxError($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
       // $username = $this->request->request('username');
        $password = $this->request->request('password');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        $type = $this->request->request('type');//1:用户 2：司机
        if (!$password) {
            $this->ajaxError('密码不能为空');
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->ajaxError('手机号格式错误');
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->ajaxError('验证码错误');
        }
        $token = $this->auth->register($mobile, $password, '', $mobile, ['type'=>$type]);
        if ($token) {
            $data = ['token' => $token];
            $this->ajaxSuccess($data);
        } else {
            $this->ajaxError($this->auth->getError());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->ajaxError(__('Operation failed'), $url);
    }

    /**
     * 忘记密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type")?:'mobile';
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("code");
        if (!$newpassword || !$captcha) {
            $this->ajaxError(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->ajaxError('手机号格式错误');
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->ajaxError('手机号尚未注册');
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->ajaxError('验证码错误');
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->ajaxError(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->ajaxError(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->ajaxError(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $token = $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $data['token'] = $token;
            $this->ajaxSuccess($data);
        } else {
            $this->ajaxError($this->auth->getError());
        }
    }
}
